﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using SimpleLibrary;

namespace SimpleConfigHelper
{
    public partial class Wizard : Form
    {
        public Wizard()
        {
            InitializeComponent();
        }

        private void BtnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection Conn = new SqlConnection(this.txtConnectionString.Text))
                {
                    SqlDataAdapter Adapter = new SqlDataAdapter("select SPECIFIC_NAME as ProcedureName,ROUTINE_DEFINITION as Definition from information_schema.routines where routine_type = 'PROCEDURE'", Conn);
                    DataTable dt = new System.Data.DataTable();
                    Adapter.Fill(dt);
                    this.dgSPList.DataSource = dt;
                    this.dgSPList.Columns[0].Width = 200;
                    this.dgSPList.Columns[1].Width = 1000;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        // Generate Config File
        private void BtnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                int i = dgSPList.SelectedCells[0].RowIndex;
                string strSPName = dgSPList.Rows[i].Cells[0].Value.ToString();

                DataTable dtTable = new DataTable();
                using (SqlConnection Conn = new SqlConnection(this.txtConnectionString.Text))
                {
                    SqlDataAdapter Adapter = new SqlDataAdapter("sp_help " + strSPName, Conn);
                    DataSet ds = new System.Data.DataSet();
                    Adapter.Fill(ds);
                    dtTable = ds.Tables[1].Copy();
                }
                //Generate XML 
                StringBuilder sb = new StringBuilder();
                sb.Append("<Job name=\"" + strSPName + "\" type=\"SP\" query=\"" + strSPName + "\" dataSource=\"mydata.csv\">" + Environment.NewLine);
                foreach(DataRow dr in dtTable.Rows){
                    sb.Append("<Parameter name=\"" + dr["Parameter_Name"].ToString() + "\" type=\"" + SqlLoadGen.ConvertToDBType(dr["Type"].ToString()).ToString() + "\" dataSourceKey=\"somekey\" />" + Environment.NewLine);
                }
                sb.Append("</Job>");

                this.txtConfig.Text = sb.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
